<template>
  <el-dialog
    v-model="visible"
    :title="isEditMode ? '编辑视频' : '新增视频'"
    width="600px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
    >
      <!-- 新增模式下的视频文件上传 -->
      <el-form-item v-if="!isEditMode" label="视频文件" prop="videoFile">
        <div class="upload-button-container">
          <div class="custom-upload-button" @click="handleSelectVideoFile">
            <el-icon><Upload /></el-icon>
            <span>选择视频文件</span>
          </div>
        </div>
        <input 
          ref="videoFileInputRef" 
          type="file" 
          accept="video/*"
          style="display: none;" 
          @change="handleVideoFileSelect"
        />
        <div v-if="selectedVideoFileName" class="selected-file-info">
          已选择: {{ selectedVideoFileName }}
        </div>
      </el-form-item>
      
      <!-- 封面图片 -->
      <el-form-item label="封面图片" prop="coverImage">
        <!-- 显示当前封面预览 -->
        <div v-if="coverPreviewUrl" class="cover-preview">
          <el-image 
            :src="coverPreviewUrl" 
            class="cover-image"
            fit="cover"
            style="width: 100px; height: 100px; border-radius: 4px; margin-bottom: 10px;"
          />
        </div>
        
        <!-- 编辑模式下可以直接输入ID或选择新图片 -->
        <div class="upload-button-container">
          <div class="custom-upload-button" @click="handleSelectCoverImage">
            <el-icon><Upload /></el-icon>
            <span>{{ isEditMode ? '更换封面图片' : '选择封面图片' }}</span>
          </div>
        </div>
        
        <input 
          ref="coverImageInputRef" 
          type="file" 
          accept="image/*"
          style="display: none;" 
          @change="handleCoverImageSelect"
        />
        <div v-if="selectedCoverImageName" class="selected-file-info">
          已选择: {{ selectedCoverImageName }}
        </div>
      </el-form-item>
      
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入视频标题" />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input 
          v-model="formData.description" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入视频描述" 
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { getUploadListPage, uploadFile } from '@/api/modules/upload'
import { createShortVideo, editShortVideo } from '@/api/modules/shortVideo'
import type { ShortVideo } from '@/api/modules/shortVideo'
import type { FormInstance, FormRules } from 'element-plus'

const props = defineProps<{
  modelValue: boolean
  videoData: ShortVideo | null
  isEditMode: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)
const formRef = ref<FormInstance | null>(null)

// 视频文件上传相关（仅新增时使用）
const videoFileInputRef = ref<HTMLInputElement | null>(null)
const selectedVideoFileName = ref('')
const selectedVideoFile = ref<File | null>(null)

// 封面图片上传相关
const coverImageInputRef = ref<HTMLInputElement | null>(null)
const selectedCoverImageName = ref('')
const selectedCoverImageFile = ref<File | null>(null)

const formData = ref({
  video_id: 0,
  title: '',
  description: '',
  cover_image_id: undefined as number | undefined
})

const rules = ref<FormRules>({
  videoFile: [
    { required: true, validator: validateVideoFile, trigger: 'change' }
  ],
  title: [
    { required: false, message: '请输入视频标题', trigger: 'blur' }
  ],
  description: [
    { required: false, message: '请输入视频描述', trigger: 'blur' }
  ]
})

// 验证视频文件的自定义规则
function validateVideoFile(rule: any, value: any, callback: any) {
  if (!props.isEditMode && !selectedVideoFile.value) {
    callback(new Error('请上传视频文件'))
  } else {
    callback()
  }
}

// 封面预览URL
const coverPreviewUrl = computed(() => {
  // 如果选择了新的封面图片，优先显示新选择的图片
  if (selectedCoverImageFile.value) {
    return URL.createObjectURL(selectedCoverImageFile.value)
  }
  
  // 如果是编辑模式且有原始封面
  if (props.isEditMode && props.videoData?.cover_image?.fileurl) {
    return props.videoData.cover_image.fileurl
  }
  
  return ''
})

// 监听弹窗打开，初始化表单数据
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    if (props.isEditMode && props.videoData) {
      // 编辑模式初始化数据
      formData.value.video_id = props.videoData.video_id || 0
      formData.value.title = props.videoData.title || ''
      formData.value.description = props.videoData.description || ''
      formData.value.cover_image_id = props.videoData.cover_image_id || undefined
    } else {
      // 新增模式初始化数据
      formData.value.video_id = 0
      formData.value.title = ''
      formData.value.description = ''
      formData.value.cover_image_id = undefined
      // 重置文件选择状态
      selectedVideoFileName.value = ''
      selectedVideoFile.value = null
      selectedCoverImageName.value = ''
      selectedCoverImageFile.value = null
    }
  }
}, { immediate: true })

// 处理选择视频文件（仅新增时使用）
const handleSelectVideoFile = () => {
  if (props.isEditMode) return
  if (videoFileInputRef.value) {
    videoFileInputRef.value.click()
  }
}

// 处理视频文件选择（仅新增时使用）
const handleVideoFileSelect = (event: any) => {
  if (props.isEditMode) return
  const input = event.target as HTMLInputElement
  if (input.files && input.files.length > 0) {
    selectedVideoFile.value = input.files[0]
    selectedVideoFileName.value = input.files[0].name
    // 清空input的value，以便下次选择相同文件时也能触发change事件
    input.value = ''
    
    // 验证表单以更新验证状态
    formRef.value?.validateField('videoFile')
  }
}

// 处理选择封面图片
const handleSelectCoverImage = () => {
  if (coverImageInputRef.value) {
    coverImageInputRef.value.click()
  }
}

// 处理封面图片选择
const handleCoverImageSelect = (event: any) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files.length > 0) {
    selectedCoverImageFile.value = input.files[0]
    selectedCoverImageName.value = input.files[0].name
    // 清空input的value，以便下次选择相同文件时也能触发change事件
    input.value = ''
  }
}

// 上传视频文件
const uploadVideoFile = async (): Promise<number> => {
  if (!selectedVideoFile.value) {
    throw new Error('未选择视频文件')
  }

  const formData = new FormData()
  formData.append('file', selectedVideoFile.value)

  try {
    const response = await uploadFile(formData)
    if (response.data && response.data.upload_id) {
      return response.data.upload_id
    } else {
      throw new Error('视频上传失败')
    }
  } catch (error) {
    console.error('视频上传失败:', error)
    throw error
  }
}

// 上传封面图片
const uploadCoverImage = async (): Promise<number> => {
  if (!selectedCoverImageFile.value) {
    // 如果是编辑模式且没有选择新图片，返回原有的图片ID
    if (props.isEditMode && props.videoData?.cover_image_id) {
      return Promise.resolve(props.videoData.cover_image_id);
    }
    return Promise.resolve(0); // 没有选择封面图片，返回0
  }

  const formData = new FormData()
  formData.append('file', selectedCoverImageFile.value)

  try {
    const response = await uploadFile(formData)
    if (response.data && response.data.upload_id) {
      return response.data.upload_id
    } else {
      throw new Error('封面图片上传失败')
    }
  } catch (error) {
    console.error('封面图片上传失败:', error)
    throw error
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        if (props.isEditMode) {
          // 编辑视频
          let coverImageId = formData.value.cover_image_id;
          
          // 如果用户选择了新的封面图片，则上传新图片并使用新ID
          if (selectedCoverImageFile.value) {
            coverImageId = await uploadCoverImage();
          }
          
          await editShortVideo({
            video_id: formData.value.video_id,
            title: formData.value.title,
            description: formData.value.description,
            cover_image_id: coverImageId
          })
          ElMessage.success('编辑成功')
        } else {
          // 新增视频 - 先上传文件再创建记录
          if (!selectedVideoFile.value) {
            ElMessage.error('请上传视频文件')
            loading.value = false
            return
          }
          
          // 上传封面图片
          const coverImageId = await uploadCoverImage()
          
          // 上传视频文件
          const videoUploadId = await uploadVideoFile()
          
          // 创建视频记录
          await createShortVideo({
            title: formData.value.title,
            description: formData.value.description,
            cover_image_id: coverImageId || undefined,
            video_upload_id: videoUploadId
          })
          ElMessage.success('新增成功')
        }
        
        handleClose()
        emit('success')
      } catch (error) {
        console.error(`${props.isEditMode ? '编辑' : '新增'}视频失败:`, error)
      } finally {
        loading.value = false
      }
    }
  })
}

// 处理关闭弹窗
const handleClose = () => {
  visible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
  // 重置文件选择状态
  selectedVideoFileName.value = ''
  selectedVideoFile.value = null
  selectedCoverImageName.value = ''
  selectedCoverImageFile.value = null
  formData.value.cover_image_id = undefined
  
  // 清空文件输入框
  if (videoFileInputRef.value) {
    videoFileInputRef.value.value = ''
  }
  if (coverImageInputRef.value) {
    coverImageInputRef.value.value = ''
  }
}
</script>

<style scoped>
.selected-file-info {
  margin-top: 10px;
  font-size: 12px;
  color: #67c23a;
}

.cover-preview {
  text-align: center;
}

.custom-upload-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 12px 20px;
  border-radius: 6px;
  border: 1px dashed #409eff;
  background-color: #ecf5ff;
  color: #409eff;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.custom-upload-button:hover {
  background-color: #409eff;
  color: white;
}

.custom-upload-button .el-icon {
  margin-right: 8px;
}

.upload-button-container {
  display: inline-block;
  margin-bottom: 10px;
}
</style>